<template>
	<view class="layout">
		<view class="title">添加一级分类</view>
		<view class="form">
			<view class="opt">
				<text class="label">名称:</text>
				<input v-model="input" class="input" type="text" placeholder="请输入一级分类">
			</view>
			<view class="opt">
				<button @click="addCategoryFn" class="button">添加</button>
			</view>
		</view>
		<view class="table table-1">
			<view class="tr">
				<view class="th">序号</view>
				<view class="th">名称</view>
				<view class="th">操作</view>
			</view>

			<view class="tr" v-for="(item,index) in arr">
				<view class="td">{{index + 1}}</view>
				<view class="td">{{item.text}}</view>
				<view class="td">
					<text class="txt" @click="removeCategory(item._id)">删除</text>
				</view>
			</view>

		</view>
		<view class="msg" v-if="arr.length == 0">
			<text>暂无一级分类~~</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';


	const input = ref("");
	const arr = ref([])

	const db = uniCloud.database();
	const categoryCollection = db.collection("categorys");
	
	
	
	
	// 获取一级分类
	const listCategory = async ()=> {
		await categoryCollection.get()
		.then(
			res=> {
				let result = res.result;
				arr.value = result.data;
			}
		)
		.catch(err => console.log(err))
	}
	
	// 编写方法删除分类
	const removeFn = async (id)=> {
		await categoryCollection.where({_id: id}).remove()
		.then(
			res=> {
				let result = res.result;
				if(result.errCode == 0) {
					listCategory();
				}
			}
		)
		.catch(err => console.log(err))
	}
	
	// 点击行为，删除一级分类
	const removeCategory = async (id)=> {
		uni.showModal({
			title:"警告",
			content:"你要删除这个分类?",
			success(content){
				if(content.confirm) {
					// 表示点击了“确定”
					removeFn(id);
				}
			}
		})
	}
	
	
	// 添加一级分类
	const addCategoryFn = async () => {
		let text = input.value;
		if (text == "") {
			uni.showToast({
				title: "输入框不能为空",
				icon: "none"
			})
			return false;
		}

		await categoryCollection.where({
				text: text
			}).get()
			.then(
				async (res) => {
					let result = res.result;
					console.log("查询结果:", result)
					if (result.data.length == 0) {
						await categoryCollection.add({
								text: text
							})
							.then(
								res => {
									if (res.result.errCode == 0) {
										uni.showToast({
											title: "添加一级菜单成功",
											icon: "none"
										})
										// 重置输入框
										input.value = "";
										// 获取列表 
										listCategory();
									} else {
										uni.showToast({
											title: "添加失败",
											icon: "none"
										})
									}
								}
							)
							.catch(err => console.log(err))
					} else {
						uni.showToast({
							title: "该分类已经存在~~",
							icon: "none"
						})
					}
				}
			)
			.catch(err => console.log(err))


	}



	// 初始化页面
	listCategory();
</script>

<style lang="scss">
	@import "../topic.scss";
</style>